<template>
    <el-form :model="loginForm" ref="form" label-width="100px" :inline="false" size="default">
        <el-form-item label="请输入账号">
            <el-input v-model="loginForm.user_id"></el-input>
        </el-form-item>
        <el-form-item label="请输入密码">
            <el-input v-model="loginForm.password" type="password"></el-input>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="onSubmit">登录</el-button>
            <el-button>取消</el-button>
        </el-form-item>
    </el-form>

</template>

<script setup>
import { ref } from 'vue';
import axios from 'axios';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus'
import { useCounterStore } from '@/stores/counter'
	const counter = useCounterStore()
	// counter.count++
	// // 自动补全！ ✨
	// counter.$patch({ count: counter.count + 1 })
	// // 或使用 action 代替
	// counter.increment()

const loginForm = ref(
    {
        user_id: '',
        password: ''
    }
)

// const token = ref('')

const router = useRouter();

const onSubmit = () => {
    axios.post("http://localhost:5000/login", loginForm.value)
    .then((res) => {
        sessionStorage.setItem('token', res.data.token);
        const token = sessionStorage.getItem('token');
        console.log(token);
        console.log(res);
        // 登录成功
        if (res.data.status === 'success') {
            // 导航至工作单页面
            // isLogin.value = true;
            counter.set_userName(res.data.user_name)
            counter.get_role(res.data.role_id)
            counter.get_userId(res.data.user_id)
            console.log('312')
            counter.login()
            router.push('/worklist')
            
        }
        // 登录失败
        else {
            ElMessage({
                message: '用户不存在或密码错误',
                type: 'warning',
            })
        }
    })
    .catch((error) => {
        // console.error('login failed', error.res.data);
    })
    
}
</script>
 
<style lang="scss" scoped>

</style>